// 状态映射表
const statusMap = {
	3: { class: 'status-success', text: '已使用' },
	2: { class: 'status-error', text: '已校验' },
	1: { class: 'status-pending', text: '待使用' }
};

// 验证码类型映射
// 验证码类型映射
const typeMap = {
	1: "注册验证码",
	2: "找回登录密码",
	3: "找回交易密码",
	4: "修改手机号码第一步",
	5: "修改手机号码第二步",
	6: "添加邮箱",
	7: "修改邮箱",
	10: "见证人为客户创建账号验证码",
	11: "第三方社交账号绑定",
	12: "第三方社交账号直接绑定",
	13: "登录密码初始设置",
	14: "第三方授权认证",
	15: "第三方快速登录",
	16: "用户设备绑定",
	17: "用户交易登录",
	18: "投顾-找回登录密码",
	19: "投顾-手机快速登录",
	20: "修改双因素验证",
	21: "身份验证",
	22: "開戶-香港PAD見證-簽名上傳",
	23: "验证码登录注册",
	24: "找回交易账号",
	25: "快速登录",
	26: "修改开户邮箱",
	27: "第三方sdk找回交易密码",
	28: "通用验证码",
	29: "添加证券邮箱",
	30: "修改证券邮箱-验证原邮箱",
	31: "修改证券邮箱-验证新邮件",
	32: "修改证券邮箱-废弃",
	33: "企业portal-修改资料",
	34: "企业portal-添加银行卡",
	35: "企业portal-存入资金",
	36: "企业portal-取出资金",
	37: "企业portal-资金内转",
	38: "企业portal-证期互转",
	39: "企业portal-货币兑换",
	40: "企业portal-股票转入",
	41: "企业portal-股票转出",
	42: "企业portal-股票内转",
	43: "企业portal-基金内转",
	44: "企业portal-债券内转"
};
// 数据请求函数
async function fetchData() {
	// 显示加载动画
	const phone = document.querySelector('.phone-filter').value.trim();
	let env = document.querySelector('.env-filter').value;
	// 显示加载动画
	document.querySelector('.loader').style.display = 'block';
	document.querySelector('.error-message').style.display = 'none';
	// 构造请求参数
	const params = new URLSearchParams();
	if (phone) params.append('mobile', phone);
	if (!env){
		env = "feature";
	}
	params.append('profile', env); // 假设profile对应环境参数
	const url = `https://admin-feature.vbkrhk.com/auto-ai/sms/list?${params}`;
	try {
		const response = await fetch(url);
		const data = await response.json();
		// 隐藏加载动画
		document.querySelector('.loader').style.display = 'none';
		if (data.code === 0) {
			renderTable(data.data);
		} else {
			document.querySelector('.error-message').textContent = data.msg || '请求失败';
			document.querySelector('.error-message').style.display = 'block';
		}
	} catch (error) {

		document.querySelector('.error-message').textContent = '网络错误';
		document.querySelector('.error-message').style.display = 'block';
	}
}
// 复制事件处理函数
function handleCopy(event) {
	const text = event.target.textContent.trim();
	if (!text) return;

	// 复制到剪贴板
	navigator.clipboard.writeText(text)
		.then(() => {
			console.log('✅ 复制成功:', text);
			// 可选：添加视觉反馈（如高亮单元格）
			event.target.style.backgroundColor = '#eaffea';
			setTimeout(() => {
				event.target.style.backgroundColor = '';
			}, 1000);
		})
		.catch(error => {
			console.error('❌ 复制失败:', error);
		});
}
// 表格渲染函数
function renderTable(data) {
	const tbody = document.querySelector('tbody');
	tbody.innerHTML = ''; // 清空原有数据
	data.forEach(item => {
		const row = document.createElement('tr');

		const mobileCell = document.createElement('td');
		mobileCell.textContent = item.mobile;
		row.appendChild(mobileCell);

		const codeCell = document.createElement('td');
		codeCell.textContent = item.auth_code;
		// 绑定复制事件（单击或双击）
		codeCell.addEventListener('click', handleCopy);
		codeCell.addEventListener('dblclick', handleCopy);
		row.appendChild(codeCell);

		const typeCell = document.createElement('td');
		typeCell.textContent = typeMap[item.auth_type] || '未知';
		row.appendChild(typeCell);

		const statusCell = document.createElement('td');
		const statusSpan = document.createElement('span');
		statusSpan.className = `status ${statusMap[item.use_status]?.class || 'status-pending'}`;
		statusSpan.textContent = statusMap[item.use_status]?.text || '未知';
		statusCell.appendChild(statusSpan);
		row.appendChild(statusCell);

		const memberIdCell = document.createElement('td');
		memberIdCell.textContent = item.member_id || '无';
		row.appendChild(memberIdCell);

		tbody.appendChild(row);
	});
}

document.getElementById('filter-btn').addEventListener('click', function() {
	fetchData();
});

// panel.js
document.addEventListener("DOMContentLoaded", async () => {
	try {
		// 获取当前页面的 URL
		const url = await new Promise((resolve) => {
			chrome.devtools.inspectedWindow.eval(
				"location.href",
				(result, isException) => {
					if (isException) {
						resolve("无法获取 URL");
					} else {
						resolve(result);
					}
				}
			);
		});

		// 检测 URL 是否包含 "feature"
		const containsFeature = url.includes("feature");
		const containsDaily = url.includes("daily");
		// 获取 select 元素
		const envSelect = document.querySelector('.env-filter');
		// 设置选中值为 "feature"
		let profile = null;
		if (containsDaily) {
			profile = 'daily';
			envSelect.value = 'daily';
		}else if (containsFeature) {
			profile = 'feature';
			envSelect.value = 'feature';
		}
		const environmentMessage = document.querySelector('.environment-message');
		environmentMessage.innerHTML = `
				检测您当前环境为 
				<span class="current-env">${profile}</span> 
					环境，如下是 
				<span class="current-env">${profile}</span> 
				环境最新5条
					`;
		fetchData(); // 页面加载时自动获取数据
		const intervalId = setInterval(() => {
			// 要执行的代码
			fetchData();
		}, 1000); // 3000 毫秒 = 3秒
	} catch (error) {
		console.error("错误:", error);
		document.getElementById("result").innerText = "检测失败，请重试。";
	}
});
var myconsole =
{
	_log: function(obj)
	{
		// 不知为何，这种方式不行
		chrome.devtools.inspectedWindow('console.log('+JSON.stringify(obj)+')');
	},
	log: function(obj)
	{
		// 这里有待完善
		chrome.tabs.executeScript(chrome.devtools.inspectedWindow.tabId, {code: 'console.log(' + JSON.stringify(obj) + ')'}, function(){});
	}
};
